# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import logging

from django.contrib.auth import (login as auth_login, logout as auth_logout)
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from wenlincms.utils.models import get_user_model
from wenlincms.utils.urls import next_url
from wenlincms.utils.views import render

from wlapps.accounts.forms import LoginForm, SignupForm, RandomCodeVerifyForm

User = get_user_model()
add_log = logging.getLogger('error')


# 登入
@csrf_exempt
@never_cache
def login(request):
    if request.user.is_authenticated():
        return redirect('/saas/')
    else:
        form = LoginForm(request.POST or None)
        if request.method == "POST" and form.is_valid():
            authenticated_user = form.save()
            auth_login(request, authenticated_user)
            return redirect('/saas/')
        context = {"form": form, "title": _("Log in")}
        return render(request, "saas/accounts/login.html", context)


# 登出
@never_cache
def logout(request):
    auth_logout(request)
    return redirect(next_url(request) or get_script_prefix())


# 注册
@never_cache
@csrf_exempt
def signup(request):
    if request.user.is_authenticated():
        return redirect('/saas/')
    else:
        signup_form = SignupForm(request.POST or None, request.FILES or None)
        random_code_form = RandomCodeVerifyForm(request.POST or None)
        # 渲染注册页面
        if request.method == 'GET':
            context = {"form": signup_form, "title": "注册", "random_code": random_code_form}
            return render(request, "saas/accounts/signup.html", context)
        # 注册页面表单提交
        if request.method == "POST" and signup_form.is_valid():
            signup_form.save()
            return HttpResponse(json.dumps({'status': 1}), content_type="application/json")
        else:
            return HttpResponse(json.dumps({'status': signup_form.errors}), content_type="application/json")


@login_required
def account_redirect(request):
    return HttpResponseRedirect("/saas/")


# 校验用户名是否已被注册
@never_cache
def judge_username_exist(request):
    username = request.GET.get("username")
    data = dict()
    if username:
        texist = User.objects.filter(username=username).count()
        texist = 1 if texist > 0 else 0
        data['tExist'] = texist
    return HttpResponse(json.dumps(data), content_type="application/json")


# 校验图片验证码
@csrf_exempt
@never_cache
def verify_random_code(request):
    random_code_form = RandomCodeVerifyForm(request.POST or None)
    if request.method == "POST":
        if random_code_form.is_valid():
            return HttpResponse(json.dumps({"random_code_return": 1}), content_type="application/json")
        else:
            return HttpResponse(json.dumps({"random_code_return": 0}), content_type="application/json")


# todo  更改帐号密码
@login_required
def change_pwd(request):
    return render(request, "saas/accounts/login.html", {})


# todo  管理该账户下的子帐号
@login_required
def manage_user(request):
    return render(request, "saas/accounts/login.html", {})


# todo  创建该账户下的子帐号
@login_required
def create_user(request):
    return render(request, "saas/accounts/login.html", {})


# todo  修改该账户下的子帐号
@login_required
def change_user(request):
    return render(request, "saas/accounts/login.html", {})


# todo  删除该账户下的子帐号，更改子帐号下所属帐号的状态
@login_required
def delete_user(request):
    return render(request, "saas/accounts/login.html", {})